package com.lch.webdemo.filter;

import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <一句话描述>.
 *
 * @author liuchenhui
 * @date 2018/10/22
 * @since
 */
public class CommonFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        String uri = httpRequest.getRequestURI();

        if (uri != null) {
            if (uri.startsWith("/js/") || uri.contains("mstatic")) {
                httpResponse.setHeader("Cache-Control", "max-age=315360000");
            } else {
                if (httpRequest.getMethod().equalsIgnoreCase(HttpMethod.GET.name())) {
                    // 设置返回头不缓存
                    httpResponse.setHeader("Cache-Control", "no-cache, no-store, private, must-revalidate, proxy-revalidate");
                    httpResponse.setHeader("Pragma", "no-cache");
                }
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
